package org.jeecg.modules.hkvs;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.xml.ws.ServiceMode;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Service
@Slf4j
public class HaikService {
    public HaikService() {
        ArtemisConfig.host = "10.2.102.175:443"; // artemis网关服务器ip端口
        ArtemisConfig.appKey = "22239369";  // 秘钥appkey
        ArtemisConfig.appSecret = "rEeReTsOYRyFRUaXSRXF";// 秘钥appSecret
    }

    // 获取全部人脸数据
    List<HaikYitstjg> renyList() {
        Map<String, String> path = new HashMap<String, String>() {
            {
                put("https://", "/artemis/api/frs/v1/face");//根据现场环境部署确认是http还是https
            }
        };

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 1000);

        String body = jsonBody.toJSONString();

        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
        log.info("result>>>"+result);
        HaikRtn2 haikRtn = JSON.parseObject(result, new TypeReference<HaikRtn2>(){});
        log.info("haikRtn>>>"+haikRtn);
        if(haikRtn != null) {
            HaikFenyYitstjg data = haikRtn.getData();
            if(data != null && data.list.size() > 0) {
                return data.getList();
            }
        }

        return null;
    }

    // 批量删除人脸，一次只能删1000
    public String batchDelete() {
        List indexCodes = new ArrayList();
        log.info("renyList()>>>"+renyList().toString());
        renyList().stream().forEach(e-> {
            String indexCode = e.getIndexCode();
            indexCodes.add(indexCode);
        });

        Map<String, String> path = new HashMap<String, String>() {
            {
                put("https://", "/artemis/api/frs/v1/face/deletion");//根据现场环境部署确认是http还是https
            }
        };

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("indexCodes", indexCodes);
        jsonBody.put("faceGroupIndexCode", "7549ee5d7a11463e8e3c0b09255d0590");

        String body = jsonBody.toJSONString();

        return ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
    }

    // 人脸分组1VN检索
    public HaikYitstjg oneToMany(String facePicUrl) {
        Map<String, String> path = new HashMap<String, String>() {
            {
                put("https://", "/artemis/api/frs/v1/application/oneToMany");//根据现场环境部署确认是http还是https
            }
        };

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("minSimilarity", 50);
        jsonBody.put("facePicUrl", facePicUrl);
        jsonBody.put("faceGroupIndexCodes", new ArrayList<String>(){{
            add("7549ee5d7a11463e8e3c0b09255d0590");
        }});

        String body = jsonBody.toJSONString();

        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
        System.out.println(result);

        HaikRtn2 haikRtn = JSON.parseObject(result, new TypeReference<HaikRtn2>(){});
        if(haikRtn != null) {
            HaikFenyYitstjg data = haikRtn.getData();
            if(data != null && data.list.size() > 0) {
                List<HaikYitstjg> list = data.getList();
                Optional<HaikYitstjg> haikYitstjg = list.stream().max(Comparator.comparingDouble(HaikYitstjg::getSimilarity));
                return haikYitstjg.get();
            }
        }

        return null;
    }

    // "orgIndexCode":"root000000"
    public String getOrgIndexCode() {
        Map<String, String> path = new HashMap<String, String>() {
            {
                put("https://", "/artemis/api/resource/v1/org/rootOrg");//根据现场环境部署确认是http还是https
            }
        };

        String result = ArtemisHttpUtil.doPostStringArtemis(path, "", null, null, "application/json", null);
        System.out.println(result);

        return result;
    }

    // 添加人脸
    public String addition(String name, String certificateNum, String facePicUrl) {
        log.info("添加人脸开始...");
        Map<String, String> path = new HashMap<String, String>() {
            {
                put("https://", "/artemis/api/frs/v1/face/single/addition");//根据现场环境部署确认是http还是https
            }
        };

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("faceGroupIndexCode", "7549ee5d7a11463e8e3c0b09255d0590");

        JSONObject faceInfo = new JSONObject();
        faceInfo.put("name", name);
        faceInfo.put("certificateNum", certificateNum);
        jsonBody.put("faceInfo", faceInfo);
log.info(faceInfo.toString());
        JSONObject facePic = new JSONObject();
        facePic.put("faceUrl", facePicUrl);


        String base64 = "";
        try {
             base64=getImageByPath(facePicUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("base64"+base64);
        facePic.put("faceBinaryData", base64);

        jsonBody.put("facePic", facePic);

        String body = jsonBody.toJSONString();
        log.info("添加人脸参数"+path+body);


        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
        log.info("添加人脸返回>>> ", result);
        log.info(result);
        return result;
    }

    public List face_captureSearch(String starTime, String endTime) {
        Map<String, String> path = new HashMap<String, String>() {
            {
                put("https://", "/artemis/api/frs/v1/event/face_capture/search");//根据现场环境部署确认是http还是https
            }
        };

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 1000);
        jsonBody.put("startTime", starTime);
        jsonBody.put("endTime", endTime);

        String body = jsonBody.toJSONString();
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
        System.out.println(result);
        HaikRtn haikRtn = JSON.parseObject(result, new TypeReference<HaikRtn>(){});
        if(haikRtn != null) {
            HaikFenyData data = haikRtn.getData();
            if(data != null)
                return data.getList();
        }

        return null;
    }

    public static String getImageByPath(String path) throws IOException {
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        try {
            // 创建URL
            URL url = new URL(path);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            if(conn.getResponseCode() != 200) {
                return "fail";//连接失败/链接失效/图片不存在
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while ((len = inStream.read(data)) != -1) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        byte[] encode = Base64.getEncoder().encode(outPut.toByteArray());
        String res = new String(encode);
        return res;
    }
}

